var express = require("express");
var router = express.Router();
var db = require("../db/index");

router.get('/info', function (req, res) {
  let {society_id, pageNo, limit} = req.query;
  let start = (pageNo - 1) * limit;
  let sql = `SELECT ap.*,a.name,a.stu_code FROM apply ap JOIN account a ON ap.user_id = a.id WHERE ap.society_id = ${society_id} AND ap.done = 0 ORDER BY ap.id DESC LIMIT ${start},${limit}`
  db.query(sql, function (err, rows) {
    db.query(`SELECT count(id) as total FROM apply WHERE society_id = ${society_id} AND done = 0`, function (err2, [{total}]) {
      res.send({
        code: 200,
        message: 'ok',
        list: rows,
        total
      })
    })
  })
})

router.get('/info/processed', function (req, res) {
  let {society_id, pageNo, limit} = req.query;
  let start = (pageNo - 1) * limit;
  let sql = `SELECT ap.*,a.name,a.stu_code FROM apply ap JOIN account a ON ap.user_id = a.id WHERE ap.society_id = ${society_id} AND ap.done <> 0 ORDER BY ap.id DESC LIMIT ${start},${limit}`
  db.query(sql, function (err, rows) {
    db.query(`SELECT count(id) as total FROM apply WHERE society_id = ${society_id} AND done <> 0`, function (err2, [{total}]) {
      res.send({
        code: 200,
        message: 'ok',
        list: rows,
        total
      })
    })
  })
})

// apply表 done：0表示暂未处理申请 1表示加入该社团 2表示被拒绝 3表示已被其他社团录取
router.get('/agree', function (req, res) {
  let {society_id, user_id} = req.query;
  let sql = `UPDATE apply SET done = 3 WHERE user_id = ?`
  let sql2 = `UPDATE apply SET done = 1 WHERE user_id = ? AND society_id=?`
  let sql3 = `UPDATE account SET society_id = ? WHERE id = ?`
  db.query(sql, [user_id], function (err) {
    db.query(sql2, [user_id, society_id], function (err2) {
      db.query(sql3, [society_id, user_id], function (err3) {
        res.send({
          code: 200,
          message: 'success'
        })
      })
    })
  })
})

router.get('/reduce', function (req, res) {
  let {society_id, user_id} = req.query;
  let sql = `UPDATE apply SET done = 2 WHERE user_id = ? AND society_id=?`
  db.query(sql, [user_id, society_id], function (err) {
    res.send({
      code: 200,
      message: 'success'
    })
  })
})

module.exports = router;
